<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import {
  adminGetPaperByIdService,
  adminGetQuestionsService,
  adminSaveTestPaperService,
  adminSaveTestQuestionsService
} from '@/api/admin'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { useCountStore } from '@/stores/TeaStatisticsCount'

const route = useRoute()
const testId = ref<number>(route.params.id)

const durationTime = ref([])
const paper = ref({
  id: '',
  title: '',
  testTime: '',
  beginTime: durationTime.value[0] || '',
  endTime: durationTime.value[1] || '',
  status: 0,
  createTime: '',
  updateTime: ''
})

watchEffect(() => {
  paper.value.beginTime = durationTime.value[0]
  paper.value.endTime = durationTime.value[1]
})

// 表格数据和题目信息
const questions = ref<
  Array<{
    id: number
    title: string
    options: Record<string, string>
    correctAnswer: string
    explanation: string
  }>
>([])

const getQuestions = async () => {
  if (testId.value !== 0) {
    let res = await adminGetPaperByIdService(testId.value)
    durationTime.value[0] = dayjs(res.data.data.beginTime).format('YYYY-MM-DD')
    durationTime.value[1] = dayjs(res.data.data.endTime).format('YYYY-MM-DD')
    console.log(res.data.data)
    paper.value = res.data.data
    res = await adminGetQuestionsService(testId.value)
    questions.value = res.data.data
    console.log(res.data.data)
  }
}

getQuestions()

// 当前编辑的题目
const dialogVisible = ref(false)
const currentQuestion = ref({
  id: 0,
  title: '',
  options: {} as Record<string, string>,
  correctAnswer: '',
  explanation: ''
})
const currentIndex = ref<number | null>(null)

// 新增题目
const addQuestion = () => {
  const newId = questions.value.length + 1
  questions.value.push({
    id: newId,
    title: '',
    options: {},
    correctAnswer: '',
    explanation: ''
  })
  ElMessage.success('题目新增成功！')
}

// 编辑题目
const editQuestion = (index: number) => {
  currentIndex.value = index
  currentQuestion.value = { ...questions.value[index] }
  dialogVisible.value = true
}

// 保存题目
const saveQuestion = () => {
  if (currentIndex.value !== null) {
    questions.value[currentIndex.value] = { ...currentQuestion.value }
    ElMessage.success('题目保存成功！')
  }
  dialogVisible.value = false
}

// 添加选项
const addOption = () => {
  const optionKey = String.fromCharCode(65 + Object.keys(currentQuestion.value.options).length) // A, B, C...
  currentQuestion.value.options[optionKey] = ''
}

// 删除题目
const deleteQuestion = (index: number) => {
  questions.value.splice(index, 1)
  ElMessage.success('题目删除成功！')
}

// 保存试卷
const saveQuestions = async () => {
  if (!paper.value.beginTime || !paper.value.endTime){
    ElMessage.error('请选择考试时间')
    return
  }
  const res = await adminSaveTestPaperService(paper.value)
  console.log(res.data.data)
  paper.value.id = res.data.data
  await adminSaveTestQuestionsService(questions.value, paper.value.id)
  console.log(questions.value)
  ElMessage.success('试卷保存成功！')
  await useCountStore().getContentCount()
}
</script>

<template>
  <div id="main-testCreatePage">
    <h1>试卷制作</h1>
    <div class="title-area">
      <el-input
        style="width: 300px; height: 40px; font-size: 20px"
        placeholder="请输入试卷标题"
        v-model="paper.title"
      ></el-input>
      <el-input-number
        style="width: 150px; height: 40px"
        v-model="paper.testTime"
        :min="0"
        :step="10"
        step-strictly
      />
      <el-date-picker
        v-model="durationTime"
        type="daterange"
        range-separator="至"
        start-placeholder="Start date"
        end-placeholder="End date"
        size="large"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </div>
    <!-- 题目表格 -->
    <el-scrollbar height="80vh">
      <el-table :data="questions" border style="width: 100%">
        <!-- 第二列：题目 -->
        <el-table-column label="题目内容">
          <template #default="{ $index }">
            <el-input v-model="questions[$index].title" placeholder="请输入题目内容" />
          </template>
        </el-table-column>

        <!-- 第三列：操作 -->
        <el-table-column label="操作">
          <template #default="{ $index }">
            <el-button type="text" @click="editQuestion($index)">编辑</el-button>
            <el-button type="text" @click="deleteQuestion($index)" style="color: red"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增题目按钮 -->
      <div class="btn-area">
        <el-button type="primary" @click="addQuestion">新增题目</el-button>
        <el-button type="success" @click="saveQuestions">保存试卷</el-button>
      </div>
    </el-scrollbar>
    <!-- 弹窗：编辑题目 -->
    <el-dialog append-to-body v-model="dialogVisible" title="编辑题目">
      <el-form>
        <el-form-item label="题目内容">
          <el-input v-model="currentQuestion.title" placeholder="请输入题目内容" disabled />
        </el-form-item>
        <el-form-item label="选项">
          <div v-for="(option, key) in currentQuestion.options" :key="key">
            <el-input
              style="width: 400px"
              v-model="currentQuestion.options[key]"
              :placeholder="`选项${key.toUpperCase()}`"
            />
          </div>
          <el-button @click="addOption">添加选项</el-button>
        </el-form-item>
        <el-form-item label="正确答案">
          <el-select
            style="width: 200px"
            v-model="currentQuestion.correctAnswer"
            placeholder="请选择正确答案"
          >
            <el-option
              v-for="(option, key) in currentQuestion.options"
              :key="key"
              :label="key"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="解析">
          <el-input
            v-model="currentQuestion.explanation"
            type="textarea"
            placeholder="请输入解析"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveQuestion">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
#main-testCreatePage {
  padding: 20px;
}

.title-area {
  display: flex;
  align-items: center;
  height: 100px;
}

.btn-area {
  margin-top: 20px;
}
</style>
